package com.stars.easyms.base.interceptor;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * <p>className: AbstractEasyMsJdkMethodInterceptor</p>
 * <p>description: 方法拦截器抽象类</p>
 *
 * @author guoguifang
 * @version 1.7.3
 * @date 2021/3/25 7:45 下午
 */
public interface EasyMsJdkMethodInterceptor extends InvocationHandler {

    @Override
    default Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (ReflectionUtils.isEqualsMethod(method)) {
            return proxy == args[0];
        } else if (ReflectionUtils.isHashCodeMethod(method)) {
            return System.identityHashCode(proxy);
        } else if (ReflectionUtils.isToStringMethod(method)) {
            return getInterfaceType() != null ? getInterfaceType().getName() : proxy.getClass().getName()
                    + "@" + Integer.toHexString(System.identityHashCode(proxy));
        } else if (Object.class.equals(method.getDeclaringClass())) {
            return proceed(proxy, method, args);
        }

        return intercept(proxy, method, args);
    }

    /**
     * 拦截不通过时的执行方法
     */
    default Object proceed(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(proxy, args);
    }

    /**
     * 拦截成功后执行的方法
     */
    Object intercept(Object proxy, Method method, Object[] args) throws Throwable;

    Class<?> getInterfaceType();
}